#!/usr/bin/python
# -*- coding: utf-8 -*-

import Ice, IceGrid
import os, sys, thread

try:
    HOME = os.environ['FIPA']
except KeyError:
    print 'FIPA environment variable is not currently defined.'
    sys.exit(0)

SLICE = os.path.join(HOME, 'slice')
FILE = os.path.join(HOME, 'test', 'Spammer.ice')
SRC = os.path.join(HOME, 'src', 'python')
sys.path.append(SRC)
Ice.loadSlice('--all -I/usr/share/Ice/slice', ['-I' + SLICE, FILE])

import FIPA
import Test
import AgentI
from AgentI import *

class AMI_Model_receiveMessageI (object):

    def ice_response (self):
        pass

    def ice_exception (self, ex):
        print 'SpammerI: ' + str(ex)

class SpammerI (Test.Spammer, AgentI):

    def __init__ (self, name, adapter):
        AgentI.__init__(self, name, adapter)

        query = IceGrid.QueryPrx.checkedCast(adapter.getCommunicator().stringToProxy('FIPA/Query'))

        # Modify its description in the DF.
        df = FIPA.DFPrx.checkedCast(query.findObjectById(adapter.getCommunicator().stringToIdentity('DF')))
        df.modify(FIPA.DfAgentDescription(self._proxies['self'], [FIPA.ServiceDescription('spammer')]))

    def beginTest (self, useMTS, messages, messageSizeInBytes, curr):

        query = IceGrid.QueryPrx.checkedCast(curr.adapter.getCommunicator().stringToProxy('FIPA/Query'))
        df = FIPA.DFPrx.checkedCast(query.findObjectById(curr.adapter.getCommunicator().stringToIdentity('DF')))
        mts = FIPA.MTSPrx.checkedCast(query.findObjectById(curr.adapter.getCommunicator().stringToIdentity('MTS')))
        sniffer = Test.SnifferPrx.checkedCast(query.findObjectById(curr.adapter.getCommunicator().stringToIdentity('Sniffer')))

        # Look for user agents.
        users = df.search(FIPA.DfAgentDescription(None, [FIPA.ServiceDescription('user')]))

        # Spamming...
        sniffer.beginTest('spammer')

        env = FIPA.Envelope(users, self._proxies['self'])

        # Initial message...
        pay = FIPA.ACLPayload(FIPA.ACLPerformative.Confirm, 'beginning')

        pay.ontology = ''
        # Fill the content...
        for i in range (0, messageSizeInBytes):
            pay.ontology += str(i)

        m = FIPA.Message(env, pay)
        cb = AMI_Model_receiveMessageI()
        if useMTS:
            mts.receiveMessage_async(cb, m)
        else:
            for rec in users:
                rec.receiveMessage_async(cb, m)

        m.payload.content = ''    

        for i in range (0, messages - 1):
            if useMTS:
                mts.receiveMessage_async(cb, m)
            else:
                for rec in users:
                    rec.receiveMessage_async(cb, m)

        # Final message...
        m.payload.content = 'end'
        if useMTS:
            mts.receiveMessage_async(cb, m)
        else:
            for rec in users:
                rec.receiveMessage_async(cb, m)

        sniffer.endTest('spammer')
